﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Model;
using Omu.ValueInjecter;
using NetWing.Utility;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Utility;

namespace NetWing.BPM.Admin.sys.ashx
{
    /// <summary>
    /// Summary description for DepartmentHandler
    /// </summary>
    public class DepartmentHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            UserBll.Instance.CheckUserOnlingState();

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<Department>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<Department>>(json);
                rpm.CurrentContext = context;
            }
            #region 返回部分json 用编号作为ID
            if (HttpContext.Current.Request["action"] == "textlist")
            {
                string jsonStr = DepartmentBll.Instance.GetDepartmentTreegridData();
                jsonStr = jsonStr.Replace("DepartmentName", "text");
                jsonStr = jsonStr.Replace("Code", "id");
                context.Response.Write(jsonStr);
                context.Response.End();
            }
            #endregion 返回部分json 用编号作为ID

            #region 村小组模式
            if (HttpContext.Current.Request["action"] == "jsonvillage")
            {
                string sql = "SELECT     DepartmentName,code as id,parentid,code,keyid  FROM Sys_Departments  WHERE     (ParentId = 99999)";//零时sql语句
                string role = CookieHelper.GetCookie("currentURoles");
                string currentDepType = CookieHelper.GetCookie("currentDepType");
                string currentDepID = CookieHelper.GetCookie("currentDepID");
                string currentDepCode = CookieHelper.GetCookie("currentDepCode");
                string tempJson = "";
                if (currentDepType == "村小组") //假如是村小组管理员
                {
                    sql = "SELECT  DepartmentName as text,code as id,parentid,code,keyid  FROM Sys_Departments where keyid=" + currentDepID;
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = JsonConvert.SerializeObject(dt, new DataTableConverter());
                    dt.Clear();
                }
                if (currentDepType == "村委会") //假如是村委会需要把村小组列出来
                {
                    sql = "SELECT  DepartmentName,code as id,parentid,code,keyid FROM Sys_Departments where  (ParentId=" + currentDepID + " or keyid=" + currentDepID + ")";
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = NetWingHelper.TableToEasyUITreeJson(dt, "parentid", currentDepID, "keyid", "DepartmentName");
                    tempJson = "aaa" + tempJson;
                    tempJson = tempJson.Replace("aaa,\"children\":", "");
                    dt.Clear();
                }
                if (currentDepType == "乡镇/街道") //假如是乡镇街道管理员
                {
                    sql = "SELECT  DepartmentName,code as id,parentid,code,keyid FROM Sys_Departments where   (ParentId=" + currentDepID + " or keyid=" + currentDepID + " or Code like '%" + currentDepCode + "%' )";
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = NetWingHelper.TableToEasyUITreeJson(dt, "parentid", currentDepID, "keyid", "DepartmentName");
                    tempJson = "aaa" + tempJson;
                    tempJson = tempJson.Replace("aaa,\"children\":", "");
                    dt.Clear();

                }

                if (role.IndexOf("县领导") > 0 || role.IndexOf("超级管理员") > 0)
                {
                    string jsonStr = DepartmentBll.Instance.GetDepartmentTreegridData();
                    jsonStr = jsonStr.Replace("DepartmentName", "text");
                    jsonStr = jsonStr.Replace("Code", "id");
                    context.Response.Write(jsonStr);
                    context.Response.End();
                }



                //context.Response.Write(sql + "<br>" + tempJson);
                context.Response.Write(tempJson);
                context.Response.End();
            }
            #endregion 村小组模式

            #region 村委会模式
            if (HttpContext.Current.Request["action"] == "jsonstreet")
            {
                // 假如是乡镇管理员
                string sql = "SELECT     KeyId, DepartmentName as text, ParentId, Sortnum, Remark, Code as id FROM Sys_Departments  WHERE     (ParentId = 99999)";
                string role = CookieHelper.GetCookie("currentURoles");
                string currentDepType = CookieHelper.GetCookie("currentDepType");
                string currentDepID = CookieHelper.GetCookie("currentDepID");
                string tempJson = "";
                if (currentDepType == "村委会") //假如是村委会管理员
                {
                    sql = "SELECT  code as id,DepartmentName as text FROM Sys_Departments where keyid=" + currentDepID + " and  LEN(code)<=10";
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = JsonConvert.SerializeObject(dt, new DataTableConverter());
                    dt.Clear();

                }

                if (currentDepType == "乡镇/街道") //假如是乡镇街道管理员
                {
                    sql = "SELECT  DepartmentName,code as id,parentid,code,keyid FROM Sys_Departments where  LEN(code)<=10 and (ParentId=" + currentDepID + " or keyid=" + currentDepID + ")";
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = NetWingHelper.TableToEasyUITreeJson(dt, "parentid", currentDepID, "keyid", "DepartmentName");
                    tempJson = "aaa" + tempJson;
                    tempJson = tempJson.Replace("aaa,\"children\":", "");

                }

                if (role.IndexOf("县领导") > 0 || role.IndexOf("超级管理员") > 0)
                {
                    sql = "SELECT  DepartmentName,code as id,parentid,code,keyid FROM Sys_Departments where  LEN(code)<=10 ";
                    DataTable dt = SqlEasy.ExecuteDataTable(sql);
                    tempJson = NetWingHelper.TableToEasyUITreeJson(dt, "parentid", "0", "keyid", "DepartmentName");
                    tempJson = "aaa" + tempJson;
                    tempJson = tempJson.Replace("aaa,\"children\":", "");
                }

                context.Response.Write(tempJson);
                context.Response.End();
            }
            #endregion 村委会模式



            #region 返回表一条Json数据
            if (HttpContext.Current.Request["action"] == "jsontown")
            {
                //假如角色是县领导或者超级管理员
                //假如是乡镇管理员
                string sql = "SELECT     KeyId, DepartmentName as text, ParentId, Sortnum, Remark, Code as id FROM Sys_Departments  WHERE     (ParentId = 99999)";
                string role = CookieHelper.GetCookie("currentURoles");
                string currentDepType = CookieHelper.GetCookie("currentDepType");
                string currentDepID = CookieHelper.GetCookie("currentDepID");

                if (currentDepType == "乡镇/街道") //
                {
                    sql = "SELECT     KeyId, DepartmentName as text, ParentId, Sortnum, Remark, Code as id FROM Sys_Departments  WHERE     (keyid = " + currentDepID + ")";
                }

                //context.Response.Write(CookieHelper.GetCookie("currentDepID"));
                //context.Response.End();
                //a.indexOf("aaa") 是否包含字符写法

                if (role.IndexOf("县领导") > 0 || role.IndexOf("超级管理员") > 0)
                {
                    sql = "SELECT     KeyId, DepartmentName as text, ParentId, Sortnum, Remark, Code as id FROM Sys_Departments  WHERE     (ParentId = 1)";
                }

                //假如角色是县领导或者超级管理员
                DataTable dt = SqlEasy.ExecuteDataTable(sql);
                string jsonStr = JsonConvert.SerializeObject(dt, new DataTableConverter());
                context.Response.Write(jsonStr);
                context.Response.End();
            }
            #endregion 返回表一条Json数据

            switch (rpm.Action)
            {

                case "add":
                    #region 获得parentid
                    int pid = rpm.Entity.ParentId;//获得父id
                    string depType = rpm.Entity.Remark;//得到部门类型
                    string newCode = NetWingHelper.returnAutoCode(pid, depType);
                    #endregion  获得parentid
                    Department newD = new Department();
                    newD.InjectFrom(rpm.Entity);
                    newD.Code = newCode;

                    context.Response.Write(DepartmentBll.Instance.AddNewDepartment(newD));
                    break;
                case "edit":
                    Department d = new Department();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    context.Response.Write(DepartmentBll.Instance.EditDepartment(d));
                    break;
                case "delete":
                    context.Response.Write(DepartmentBll.Instance.DeleteDepartment(rpm.KeyId));
                    break;
                default:
                    context.Response.Write(DepartmentBll.Instance.GetDepartmentTreegridData());
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}